/**
 * @description router全局配置，如有必要可分文件抽离，其中asyncRoutes只有在intelligence模式下才会用到，pro版只支持remixIcon图标，具体配置请查看vip群文档
 */
import type { App } from 'vue'
import type { RouteRecordName, RouteRecordRaw } from 'vue-router'
import { createRouter, createWebHashHistory, createWebHistory } from 'vue-router'
import { authentication, base, isHashRouterMode } from '/@/config'
import { setupPermissions } from '/@/router/permissions'
import Layout from '/@vab/layouts/index.vue'

export const constantRoutes: VabRouteRecord[] = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('/@/views/login/Login.vue'),
    meta: {
      hidden: true,
    },
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('/@/views/login/Register.vue'),
    meta: {
      hidden: true,
    },
  },
  {
    path: '/password',
    name: 'Password',
    component: () => import('/@/views/login/Password.vue'),
    meta: {
      hidden: true,
    },
  },
  {
    path: '/redirect',
    name: 'Redirect',
    component: () => import('/@/views/redirect/Redirect.vue'),
    meta: {
      hidden: true,
    },
  },
  {
    path: '/403',
    name: '403',
    component: () => import('/@/views/error/403.vue'),
    meta: {
      hidden: true,
    },
  },
  {
    path: '/404',
    name: '404',
    component: () => import('/@/views/error/404.vue'),
    meta: {
      hidden: true,
    },
  },
]

export const asyncRoutes: VabRouteRecord[] = [
  {
    path: '/',
    name: 'Comapny',
    component: Layout,
    meta: {
      title: '企业查询',
      icon: 'delete-column',
      guard: ['Admin'],
      levelHidden: true,
      breadcrumbHidden: true,
    },
    children: [
      {
        path: 'companySearch',
        name: 'CompanySearch',
        component: () => import('/@/views/company/index.vue'),
        meta: {
          title: '企业查询',
          icon: 'delete-column',
          noColumn: true,
        },
      },
    ],
  },
  {
    path: '/historySearch',
    name: 'HistorySearch',
    component: Layout,
    meta: {
      title: '历史查询',
      icon: 'delete-column',
      guard: ['Admin'],
      levelHidden: true,
      breadcrumbHidden: true,
    },
    children: [
      {
        path: 'historySearch',
        name: 'HistorySearch',
        component: () => import('/@/views/company/history.vue'),
        meta: {
          title: '历史查询',
          icon: 'history-line',
          noColumn: true,
        },
      },
      {
        path: 'companyDetail',
        name: 'CompanyDetail',
        component: () => import('/@/views/company/detail.vue'),
        meta: {
          hidden: true,
          title: '详情页',
          dynamicNewTab: false, //详情页根据id传参不同可打开多个
        },
      },
      {
        path: 'logDetail',
        name: 'LogDetail',
        component: () => import('/@/views/company/log_detail.vue'),
        meta: {
          hidden: true,
          title: '日志详情',
          dynamicNewTab: false, //详情页根据id传参不同可打开多个
        },
      },
    ],
  },

  {
    path: '/companyConfig',
    name: 'CompanyConfig',
    component: Layout,
    meta: {
      title: '配置管理',
      icon: 'delete-column',
      guard: ['Admin'],
      levelHidden: true,
      breadcrumbHidden: true,
    },
    children: [
      {
        path: 'companyConfig',
        name: 'CompanyConfig',
        component: () => import('/@/views/company/config.vue'),
        meta: {
          title: '配置管理',
          icon: 'delete-column',
          noColumn: true,
        },
      },
      {
        path: 'companyConfigDetail',
        name: 'CompanyConfigDetail',
        component: () => import('/@/views/company/config_detail.vue'),
        meta: {
          hidden: true,
          title: '配置详情',
          icon: 'delete-column',
          noColumn: true,
        },
      },
    ],
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/404',
    name: 'NotFound',
    meta: {
      title: '404',
      hidden: true,
    },
  },
]

const router = createRouter({
  history: isHashRouterMode ? createWebHashHistory(base) : createWebHistory(base),
  routes: constantRoutes as RouteRecordRaw[],
})

const fatteningRoutes = (routes: VabRouteRecord[]): VabRouteRecord[] => {
  return routes.flatMap((route) => {
    return route.children ? fatteningRoutes(route.children) : route
  })
}

const addRouter = (routes: VabRouteRecord[]) => {
  routes.forEach((route: VabRouteRecord) => {
    if (!router.hasRoute(route.name)) router.addRoute(route as RouteRecordRaw)
    if (route.children) addRouter(route.children)
  })
}

export const resetRouter = (routes: VabRouteRecord[] = constantRoutes) => {
  routes.map((route: VabRouteRecord) => {
    if (route.children) route.children = fatteningRoutes(route.children)
  })
  router.getRoutes().forEach((route) => {
    if (route.name) {
      const routeName: RouteRecordName = route.name
      router.hasRoute(routeName) && router.removeRoute(routeName)
    }
  })
  addRouter(routes)
}

export const setupRouter = (app: App<Element>) => {
  if (authentication === 'intelligence') addRouter(asyncRoutes)
  // 使用后端路由时防止出现[Vue Router warn]: No match found for location with path "/index"报黄，
  // 未经全面测试请谨慎使用！建议注释掉else if中的代码，
  // else if (authentication === 'all' && isHashRouterMode) {
  //   let path = window.location.hash.slice(1)
  //   if (path === '/') path = '/index'
  //   const words = path.split('/')
  //   const lastWord: any = words.at(-1)
  //   const name = lastWord.charAt(0).toUpperCase() + lastWord.slice(1)
  //   router.addRoute({
  //     path,
  //     name,
  //     component: () => import('/@/views/index/index.vue'),
  //   })
  // }
  setupPermissions(router)
  app.use(router)
  return router
}

export default router
